import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion, CaseLevel, IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType, SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibrary]: 1,
  }
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder
  .builder()
  .caseLevel(CaseLevel.L0)
  .sign(SignType.Sign)
  .ohpmInstall(IsEnable.Enable)
  .build();

const testCaseFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  // 配置ohos.sign.har 启用 har包签名
  await commonJson5Operation(path.resolve(project.projectRootPath(), 'hvigor', 'hvigor-config.json5'), async (json5): Promise<void> => {
    json5['properties'] = {'ohos.sign.har': true};
  });

  const result = await runHvigorAsync(projectRootPath, initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHar',
    daemon: true
  }));
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 查看签名的har是否生成
  const signedHarExist =
    await fse.pathExists(path.resolve(projectRootPath, 'staticLibrary/build/default/outputs/default/staticLibrary-signed.har'));
  expect(signedHarExist).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('sign_har_stage_api11')
  .description('测试 har 包签名')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testCaseFun)
  .load();
